#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import json

from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QAbstractItemView, QTableWidgetItem, QCheckBox, QWidget, QHBoxLayout, \
    QTreeWidgetItem, QMessageBox, QMenu

import ConfigManage
import initBillParseDialog
import initRuleEditorDialog
from data_alchemy.bill_parse_regulation_alchemy import BillParseRegulationAlchemy
from initLogger import logger
from initRuleEditorDialog import RULE_EDITOR_ROW_COUNT, RULE_EDITOR_COLUMN_COUNT, RULE_EDITOR_COLUMN_CONTEXT
from ui.BillParseRuleEditorUI import Ui_Rule_Editor_Dialog



class RuleEditorDialog(QDialog,  Ui_Rule_Editor_Dialog):
    '''
    类的功能：账单解析规则添加对话框。
    '''

    def __init__(self, parent):
        super(RuleEditorDialog, self).__init__()
        #QDialog.__init__(self, parent)

        # 单独移除帮助按钮
        self.setWindowFlag(Qt.WindowContextHelpButtonHint, False)

        self.currentVoucherTextEdit = None


        self.setupUi(self)


        '''
        self.tableValesList =[]
        for selectItemField  in selectItem:
            self.tableValesList.append(selectItemField.text().strip('\t'))

        self.tableKeysList = tableKeys
        self.tableHeaderLabelsList = tableHeaderLabels

        #self.year_comboBox.addItems(init.YEAR_NAME_LIST)
        self.priority_comboBox.addItems(initBillParseDialog.RULE_PRIORITY_LIST)
        self.priority_comboBox.setCurrentIndex(2)
        '''


        self.bill_type_comboBox.addItems(initRuleEditorDialog.BILL_TYPE_LIST)
        self.bill_type_comboBox.setCurrentIndex(0)


        self.initRuleTableUI()
        self.initRuleTableData()


    def initRuleTableUI(self):
        '''
        函数功能：对解析规则表格的UI进行初始化
        :return:
        '''
        logger.debug("call initRuleTableUI function")

        self.rule_tableWidget.setRowCount(RULE_EDITOR_ROW_COUNT)  # 设置行数目
        self.rule_tableWidget.setColumnCount(RULE_EDITOR_COLUMN_COUNT)  # 设置列数目
        self.rule_tableWidget.setHorizontalHeaderLabels(RULE_EDITOR_COLUMN_CONTEXT)

        self.rule_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        self.rule_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.rule_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.rule_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.rule_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.rule_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.rule_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.rule_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

        self.rule_tableWidget.setColumnWidth(0,50)
        self.rule_tableWidget.setColumnWidth(1, 200)
        self.rule_tableWidget.setColumnWidth(2, 80)
        self.rule_tableWidget.setColumnWidth(3, 80)
        self.rule_tableWidget.setColumnWidth(4, 200)
        self.rule_tableWidget.setColumnWidth(5, 200)
        self.rule_tableWidget.setColumnWidth(6, 200)
        self.rule_tableWidget.setColumnWidth(7, 200)
        self.rule_tableWidget.setColumnWidth(8, 500)
        '''
            self.bill_parse_tableWidget.setColumnWidth(0, 80)
            self.bill_parse_tableWidget.setColumnWidth(1, 180)
            self.bill_parse_tableWidget.setColumnWidth(2, 180)
            self.bill_parse_tableWidget.setColumnWidth(3, 500)
            self.bill_parse_tableWidget.setColumnWidth(4, 100)
        '''

    def onSearch(self):
        '''
        函数功能：查询按钮响应函数
        :return:
        '''
        logger.debug("call onSearch function")
        self.clearTableContext()
        self.showBillRuleData()

    def clearTableContext(self):
        '''
        对记账凭证中表格中的内容进行清空
        :return:
        '''
        self.rule_tableWidget.clear()
        self.rule_tableWidget.setHorizontalHeaderLabels(RULE_EDITOR_COLUMN_CONTEXT)


    def initRuleTableData(self):
        '''
        函数功能：对解析规则表格数据进行初始化
        :return:
        '''

        logger.debug("call initRuleTableData function")
        self.showBillRuleData()

    def showBillRuleData(self):

        logger.debug("call showBillRuleData function")
        billParseRegulationAlchemy = BillParseRegulationAlchemy()
        billType = self.bill_type_comboBox.currentText()
        billRuleDataList= billParseRegulationAlchemy.SearchRegulationByBillType(billType)

        tableLineCount = len(billRuleDataList)
        self.rule_tableWidget.setRowCount(tableLineCount )
        for i in range(tableLineCount):
            noStr = "%d\t" % (i + 1)
            #noItem = QTableWidgetItem(noStr)
            noItem = QTableWidgetItem(str(billRuleDataList[i].id))
            self.rule_tableWidget.setItem(i, 0, noItem)



            titleItem = QTableWidgetItem(billRuleDataList[i].summary)
            self.rule_tableWidget.setItem(i, 1, titleItem)


            priorityItem = QTableWidgetItem(str(billRuleDataList[i].priority))
            self.rule_tableWidget.setItem(i, 2, priorityItem)

            isMergeItem = QTableWidgetItem(str(billRuleDataList[i].is_merge))
            self.rule_tableWidget.setItem(i, 3, isMergeItem)

            propertyIncreaseItem = QTableWidgetItem(billRuleDataList[i].property_increame_name)
            self.rule_tableWidget.setItem(i, 4, propertyIncreaseItem)

            propertyDecreaseItem = QTableWidgetItem(billRuleDataList[i].property_decrease_name)
            self.rule_tableWidget.setItem(i, 5, propertyDecreaseItem)

            ownshipIncreaseItem = QTableWidgetItem(billRuleDataList[i].ownership_increase_name)
            self.rule_tableWidget.setItem(i, 6, ownshipIncreaseItem)

            ownshipDecreaseItem = QTableWidgetItem(billRuleDataList[i].ownership_decrease_name)
            self.rule_tableWidget.setItem(i, 7, ownshipDecreaseItem)

            tempJson = json.loads(billRuleDataList[i].regulation)
            tempJsonStr = json.dumps(tempJson, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)
            ruleDetailItem = QTableWidgetItem(tempJsonStr)
            #ruleDetailItem = QTableWidgetItem(billRuleDataList[i].regulation)
            self.rule_tableWidget.setItem(i, 8, ruleDetailItem)

        #end for
        self.rule_tableWidget.resizeRowsToContents()
        #self.rule_tableWidget.resizeColumnsToContents()

    def onCustomMenu11(self, pos):
        print("dddddddd")

    def onCustomMenu(self, pos):
        '''
        函数功能：表格右键展示菜单
        :param pos:
        :return:
        '''
        logger.debug("call onCustomMenu function")
        rowNum = -1
        rowNum22=2
        for i in self.rule_tableWidget.selectionModel().selection().indexes(): #这块实现的很奇怪
            rowNum = i.row()


        logger.debug("row_num=%d"%(rowNum))
        if (rowNum < 500 and rowNum >= 0): # 表格生效的行数，501行点击右键，不会弹出菜单
            menu = QMenu() #实例化菜单
            item1 = menu.addAction(u"修改")
            item2 = menu.addAction(u"删除")
            action = menu.exec_(self.rule_tableWidget.mapToGlobal(pos))
        else:
            return


        if action == item1:
            logger.debug("修改规则")
            self.modifyRuleInfor(rowNum)
        elif action == item2:
            logger.debug("删除规则")
            self.deleteRuleInfor(rowNum)

    def deleteRuleInfor(self, rowNum):
        '''
        函数功能：处理删除解析规则菜单
        :return:
        '''
        logger.debug("call deleteVoucherAccount function")

        ruleID = self.rule_tableWidget.item(rowNum, 0).text()
        logger.debug("id=%s" % ruleID)

        billParseRegulationAlchemy = BillParseRegulationAlchemy()
        billParseRegulationAlchemy.DelRegulationItem(ruleID)
            #DelVoucherItem(ruleID)
        self.clearTableContext()
        self.showBillRuleData()



    def modifyRuleInfor(self, rowNum):
        '''
        函数功能：处理修改记账凭证菜单
        :param rowNum:
        :return:
        '''

        logger.debug("call modifyRuleInfor function")

        '''
            # 获取待修改数据的序号
            self.xuhaoNo = int(self.voucher_tableWidget.item(rowNum, 0).text())

            # 获取待修改数据的记账凭证编号信息
            self.bianhaoID = int(self.voucher_tableWidget.item(rowNum, 1).text())
            accountingVoucher = AccountVoucherAlchemy()
            voucherAccountInfo = accountingVoucher.SearchVoucheByID(self.bianhaoID)

            # 记账凭证摘要信息
            summaryText = voucherAccountInfo.summary
            self.summary_textEdit.setText(summaryText)

            # 记账凭证日期信息
            targetDatetime = voucherAccountInfo.account_date
            self.date_dateEdit.setDate(targetDatetime)

            # 资产增加名称信息
            propertyIncreaseName = voucherAccountInfo.property_increase_name
            self.property_increase_name_textEdit.setText(propertyIncreaseName)

            # 资产增加金额
            propertyIncreaseValue = voucherAccountInfo.property_increase_value
            propertyIncreaseValueStr = xstring.dispose(
                toolkit.processValueSignificant(propertyIncreaseValue)).humanized_amount(complex=True)
            self.property_increase_value_lineEdit.setText(propertyIncreaseValueStr)

            # 资产减少名称信息
            propertyDecreaseName = voucherAccountInfo.property_decrease_name
            self.property_decrease_name_textEdit.setText(propertyDecreaseName)

            # 资产减少金额
            propertyDecreaseValue = voucherAccountInfo.property_decrease_value
            propertyDecreaseValueStr = xstring.dispose(
                toolkit.processValueSignificant(propertyDecreaseValue)).humanized_amount(complex=True)
            self.property_decrease_value_lineEdit.setText(propertyDecreaseValueStr)

            # 权属增加名称信息
            ownershipIncreaseName = voucherAccountInfo.ownership_increase_name
            self.ownership_increase_name_textEdit.setText(ownershipIncreaseName)

            # 权属增加金额
            ownershipIncreaseValue = voucherAccountInfo.ownership_increase_value
            ownershipIncreaseValueStr = xstring.dispose(
                toolkit.processValueSignificant(ownershipIncreaseValue)).humanized_amount(complex=True)
            self.ownership_increase_value_lineEdit.setText(ownershipIncreaseValueStr)

            # 权属减少名称信息
            ownershipDecreaseName = voucherAccountInfo.ownership_decrease_name
            self.ownership_decrease_name_textEdit.setText(ownershipDecreaseName)

            # 权属减少金额
            ownershipDecreaseValue = voucherAccountInfo.ownership_decrease_value
            ownershipDecreaseValueStr = xstring.dispose(
                toolkit.processValueSignificant(ownershipDecreaseValue)).humanized_amount(complex=True)
            self.ownership_decrease_value_lineEdit.setText(ownershipDecreaseValueStr)

            self.add_pushButton.setText(initVoucherPage.MODIFY_BUTTON)

            '''

